package com.microwintech.boardingtreasure.common.security;

import android.content.Context;

import javax.crypto.Cipher;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

/**
 * Created by Administrator on 2014/10/22.
 */
public class SecurityUtil {
    public static PublicKey getPublicKey(Context context) {
        try {
            InputStream ins = context.getAssets().open("auline.cer");
            CertificateFactory certFactory = CertificateFactory
                    .getInstance("X.509");
            X509Certificate cert = (X509Certificate) certFactory
                    .generateCertificate(ins);
            return cert.getPublicKey();
//            String publickey = RsaHelper.encodePublicKeyToXml(cert.getPublicKey());
//            return publickey;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] encryptData(byte[] data, PublicKey pubKey) {

        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            return null;
        }
    }

    public static byte[] encryptByPublicKey(Context context, String source) {
        byte[] encryptedData = null;
        try {
            byte[] data = source.getBytes();
            CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
            InputStream bais = context.getAssets().open("auline.cer");
            X509Certificate Cert = (X509Certificate) certificatefactory.generateCertificate(bais);
            PublicKey pk = Cert.getPublicKey();
            int MAX_ENCRYPT_BLOCK = 117;
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pk);
            // return cipher.doFinal();
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            encryptedData = out.toByteArray();
            out.close();
        } catch (Exception ex) {
        }
        return encryptedData;
    }


}
